//
//  XGChatGroupViewController.m
//  HuanXin
//
//  Created by monkey on 2019/12/2.
//  Copyright © 2019 itcast. All rights reserved.
//

#import <Hyphenate/Hyphenate.h>

#import "XGChatGroupViewController.h"
#import "XGInviteTableViewController.h"
#import "XGCreateGroupViewController.h"
#import "XGJoinGroupViewController.h"

#import "XGItemModel.h"

@implementation XGChatGroupViewController

#pragma mark - 控制器生命周期方法

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"我的群组";
}

#pragma mark - 重写方法

- (NSArray<XGItemModel *> *)headerItems
{
    __weak typeof(self) weakSelf = self;
    
    XGItemModel *item1 = [XGItemModel itemModelWithTitle:@"创建群组" iconName:@"group"];
    item1.selectedCallBlock = ^(NSString *title) {
        XGInviteTableViewController *inviteViewController = [XGInviteTableViewController inviteTableViewControllerWithCompletionHandle:^(NSArray<NSString *> *userList) {
            XGCreateGroupViewController *createGroupViewController = [XGCreateGroupViewController createGroupViewControllerWithInviteUsers:userList];
            [weakSelf.navigationController pushViewController:createGroupViewController animated:YES];
        }];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:inviteViewController];
        [weakSelf presentViewController:nav animated:YES completion:nil];
    };
    
    XGItemModel *item2 = [XGItemModel itemModelWithTitle:@"加入群组" iconName:@"contact"];
    item2.selectedCallBlock = ^(NSString *title) {
        XGJoinGroupViewController *joinGroupViewController = [[XGJoinGroupViewController alloc] init];
        joinGroupViewController.joinedCallBack = ^(BOOL isJoinGroup) {
            if (isJoinGroup) {
                [weakSelf reloadTableView];
            }
        };
        [weakSelf.navigationController pushViewController:joinGroupViewController animated:YES];
    };
    return @[item1,item2];
}

- (NSArray<XGItemModel *> *)contentItems
{
    // 内内存加载
    NSArray<EMGroup *> *groups = [[EMClient sharedClient].groupManager getJoinedGroups];
    if (groups == nil || groups.count == 0) {
        EMError *error = nil;
        // 网络获取
        groups = [[EMClient sharedClient].groupManager getJoinedGroupsFromServerWithPage:1 pageSize:-1 error:&error];
        if (error != nil || groups.count == 0) {
            DEBUG_Log(@"网络获取群组失败");
            return @[];
        }
    }
    
    NSMutableArray<XGItemModel *> *groupArrM = [NSMutableArray arrayWithCapacity:groups.count];
    for (EMGroup *group in groups) {
        EMGroup *groupDetail = [[EMClient sharedClient].groupManager getGroupSpecificationFromServerWithId:group.groupId error:nil];
        [groupArrM addObject:[XGItemModel itemModelWithTitle:groupDetail.subject iconName:@"group"]];
    }
    
    return groupArrM;
}

@end
